<template>
    <el-form-item :label="label" :prop="prop" :rules="!readonly ? rules : null"
        :class="{ 'readonly-form-item': readonly }">

        <!-- 只读状态显示 -->
        <span v-if="readonly" class="readonly-content">
            {{ displayValue || '-' }}
        </span>

        <!-- 可编辑状态显示 -->
        <el-select v-else v-model="selectedInventoryTypeCode" :disabled="disabled" filterable remote clearable
            reserve-keyword :remote-method="remoteSearch" :loading="loading" :placeholder="placeholder"
            @change="handleChange">
            <el-option v-for="inventoryType in options" :key="inventoryType.code" :label="inventoryType.name"
                :value="inventoryType.code">
                <span style="float: left">{{ inventoryType.name }}</span>
            </el-option>
        </el-select>
    </el-form-item>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'
import { InventoryInOutType } from '../../engine/inventory/inventory'

export default {
    name: 'InventoryTypeSelect',
    props: {
        modelValue: {
            type: Object,
            default: null
        },
        label: {
            type: String,
            default: '类型'
        },
        prop: {
            type: String,
            default: 'inventoryType'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        readonly: {  // 新增只读属性
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '请输入关键词搜索类型'
        },
        rules: {
            type: Array,
            default: () => []
        },
        inventoryUiAction: {
            type: Object,
            required: true
        },
        inOutType: {
            type: Number,
            default: InventoryInOutType.Uknown
        }
    },
    emits: ['update:modelValue', 'change'],
    data() {
        return {
            selectedInventoryTypeCode: null,
            options: [],
            loading: false,
            lastQuery: ''
        }
    },
    computed: {
        displayValue() {  // 新增计算属性
            return this.modelValue?.name || ''
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.selectedInventoryTypeCode = val.code;
                }
            }
        }
    },
    methods: {
        async remoteSearch(query) {
            if (query === this.lastQuery) return;

            if (!this.inventoryUiAction) return;

            this.lastQuery = query;
            this.loading = true;

            try {
                const res = await this.inventoryUiAction.getInventoryTypeData({
                    pageInfo: new DataPage(1, 0, Definition.gDefualPullDownPageSize),
                    inOutType: this.inOutType
                });

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }
            } catch (error) {
                console.error('搜索类型失败:', error);
                ElMessage.error('搜索类型失败');
            } finally {
                this.loading = false;
            }
        },

        handleChange(val) {
            //console.log('inventory Type handleChange:', val)
            const selectedInventoryType = this.options.find(u => u.code === val)
            if (selectedInventoryType) {
                //console.log('inventory type selected:', selectedInventoryType)
                this.$emit('update:modelValue', selectedInventoryType)
                this.$emit('change', selectedInventoryType)
            }
        },

        async loadDefaultOptions() {

            //console.log('loadDefaultOptions this.inOutType:', this.inOutType);

            if (!this.inventoryUiAction) return;

            this.loading = true;
            try {
                const res = await this.inventoryUiAction.getInventoryTypeData({
                    pageInfo: new DataPage(1, 0, Definition.gDefualPullDownPageSize),
                    inOutType: this.inOutType
                });

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }

                //   console.log('loadDefaultOptions this.options:', this.options);
            } catch (error) {
                console.error('加载类型失败:', error);
            } finally {
                this.loading = false;
            }
        }
    },
    mounted() {

        this.$nextTick(() => {
            this.loadDefaultOptions();
        })
    }
}
</script>

<style scoped>
/* 只读状态下的表单项目样式 */
.readonly-form-item :deep(.el-form-item__label) {
    font-size: 13px;
    color: #909399;
}

.readonly-content {
    display: flex;
    align-items: center;
    width: 400px;
    padding: 0 10px;
    height: 40px;
    font-size: 15px;
    color: #303133;
    vertical-align: middle;
    margin-top: -5px;
}

/* 取消只读状态下的必填标记 */
.readonly-form-item :deep(.el-form-item__label::before) {
    content: none !important;
}
</style>